<template>
  <el-dialog v-model="dialogFormVisible" title="分配角色" width="500" draggable>
    <el-form :model="userData" @submit.prevent="handleSave">
      <el-form-item label="选择用户:" :label-width="formLabelWidth">
        <el-select v-model="userData.roleIdList" multiple placeholder="请选择用户">
          <el-option v-for="role in allRoles" :key="role.id" :label="role.name" :value="role.id"/>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave"> 确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, onMounted} from 'vue'
// import {getUserRoles, allocateUserRoles } from '@/api/user'
import {ElMessage} from "element-plus";
import {reqUserRoleList, reqAllocateUserRoles} from "@/api/userinfo.js";

// 存储用户信息
const userData = ref({
  userId: '',
  roleIdList: []
})
// 存储所有角色
const allRoles = ref([])
const dialogFormVisible = ref(false)
const formLabelWidth = '120px'

// 获取角色并展示弹窗
const showAndInit = async (userId) => {
  dialogFormVisible.value = true;
  const res = await reqUserRoleList(userId);
  if (res.data.code === '000000') {
    allRoles.value = res.data.data; // 所有角色
    userData.value.userId = userId;  // 用户id
    userData.value.roleIdList = res.data.data.filter((role) =>
        role.hasPermission).map((role) => role.id); // 用户拥有的角色
  } else {
    ElMessage.error('获取角色失败！');
  }
}

// 保存角色分配
const handleSave = async () => {
  dialogFormVisible.value = false;
  const res = await reqAllocateUserRoles(userData.value);
  if (res.data.code === '000000') {
    ElMessage.success('用户分配角色 - 操作成功！');
  } else {
    ElMessage.error('用户分配角色 - 操作失败！');
  }
}

// defineExpose 用于暴露给父组件的方法
defineExpose({
  showAndInit
})
</script>

<style scoped>

</style>
